<template>
  <el-dialog :visible.sync="dialogVisible" center width="600px">
    <!-- slot 插槽 -->
    <span class="el-dialog__title" slot="title">注 册</span>
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
      label-width="80px"
      label-position="left"
    >
      <!-- 上传头像 -->
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :data="uploadData"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <!-- 昵称 -->
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <!-- 手机 -->
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          show-password
          v-model="form.password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <!-- 图形码 -->
      <el-row>
        <el-col :span="16">
          <el-form-item label="图形码" prop="code">
            <el-input v-model="form.code" placeholder="请输入图形码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" style="margin-left: 10px">
          <img
            :src="registerCodeURL"
            style="width: 100%; height: 40px"
            @click="imgClick"
          />
        </el-col>
      </el-row>
      <!-- 验证码 -->
      <el-row>
        <el-col :span="16">
          <el-form-item label="验证码" prop="rcode">
            <el-input
              v-model="form.rcode"
              placeholder="请输入验证码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" style="margin-left: 10px">
          <el-button @click="getRcode">获取用户验证码</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- 按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="register">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "", //图片预览
      uploadUrl: `${process.env.VUE_APP_baseUrl}/uploads`, //图片上传的地址
      uploadData: {
        //上传图片附带的额外参数
        image: null,
      },
      dialogVisible: false, //控制注册弹框的
      registerCodeURL: `${process.env.VUE_APP_baseUrl}/captcha?type=sendsms&${
        new Date() - 0
      }`, //图形码的地址
      form: {
        avatar: "", //头像地址
        username: "", //昵称
        email: "",
        phone: "",
        password: "",
        code: "", //注册时的验证码
        rcode: "", //验证码
      },
      //校验
      rules: {
        avatar: [
          {
            required: true,
            message: "必须得上传头像",
            trigger: "change",
          },
        ],
        username: [
          {
            required: true,
            message: "昵称不能为空",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              //callback 是校验成功还是失败的 一定要调用
              if (!value) {
                return callback(new Error("手机号码不能为空"));
              }
              // 手机号码正则校验
              const reg = /^[1][3-9][0-9]{9}$/;
              if (!reg.test(value)) {
                return callback(new Error("手机号不合法"));
              }
              //成功了也要调用callback 但是不用传参
              callback();
            },
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              //非空判断
              if (!value) return callback(new Error("邮箱不能为空"));
              //禁用eslint
              /* eslint-disable */
              //邮箱正则
              const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
              //启用eslint
              /* eslint-enable */
              //邮箱合法判断
              if (!reg.test(value)) return callback(new Error("邮箱不合法"));
            },
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          {
            min: 6,
            max: 16,
            message: "密码长度需在6-16位之间",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "图形码不能为空",
            trigger: "blur",
          },
        ],
        rcode: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //点击图片刷新图片验证码
    imgClick() {
      this.registerCodeURL = `${
        process.env.VUE_APP_baseUrl
      }/captcha?type=sendsms&${new Date() - 0}`;
    },
    //获取短信验证码
    async getRcode() {
      let str = "";
      //判断用户是否输入了手机号和验证码
      this.$refs.form.validateField(["phone", "code"], (errorMessage) => {
        //validateField 校验部分字段
        // console.log(errorMessage);
        str += errorMessage;
      });
      // console.log(str);
      if (!str) {
        //符合条件 发送请求
        const res = await this.$axios.post(`/sendsms`, {
          phone: this.form.phone,
          code: this.form.code,
        });
        // console.log(res);
        if (res.code === 200) {
          //把获取到的验证码 弄到输入框
          this.form.rcode = res.data.captcha;
        } else {
          //提示信息
          this.$message.error(res.message);
          //刷新验证码
          this.imgClick();
        }
      }
    },
    //上传成功
    handleAvatarSuccess(res, file) {
      // console.log(res);
      if (res.code === 200) {
        //实现预览
        this.imageUrl = URL.createObjectURL(file.raw);
        //给form.avatar赋值
        this.form.avatar = res.data.file_path;
      } else {
        this.$message.error(res.message);
      }
    },
    //上传之前  --> 判断大小/格式
    beforeAvatarUpload(file) {
      //判断格式
      const idImg =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif";
      //判断大小
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!idImg) {
        this.$message.error("上传头像图片只能是 JPG/PNG/GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }

      //给上传额外参数赋值
      this.uploadData.image = file;
      return idImg && isLt2M;
    },
    //注册
    register() {
      console.log(1);
      //先整体判断一次
      this.$refs.form.validate(async vaild => {
        console.log(2);
        console.log(vaild);  //true/false
        if (!vaild) return; 
        console.log(3);
        //发送请求
        const res = await this.$axios.post("/register", this.form);
        console.log(res);
        if (res.code === 200) {
          //提示信息
          this.$message.success("注册成功");
          //关闭注册框
          this.dialogVisible = false;
        } else {
          //提示信息
          this.$message.error("注册失败");
          //刷新验证码
          this.imgClick();
        }
      });
    },
  },
};
</script>   


<style lang="less">
.el-dialog__header {
  background: linear-gradient(270deg, #01c6fa, #1493fa);
  text-align: center;
}
.el-dialog__title {
  color: #fff;
}
// 头像上传
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>